﻿using System;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web.Security.AntiXss;
using System.Web.UI;
using InhollandAir.auxiliary;

namespace InhollandAir
{
    public partial class Login : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["msg"] != null && Request["msg"] == "1") lblLoginResult.Text = AntiXssEncoder.HtmlEncode("Account created, please log in.", false);

            CustomerFactory.TryLogin((customer, success) =>
                {
                    if(success) Response.Redirect("Account.aspx");
                });

            if(Page.IsPostBack)
                txtPassword.Focus();
            else
                txtUserName.Focus();
        }

        protected void BtnSubmitClick(object sender, EventArgs e)
        {
            Thread.Sleep(1500);
            const string errorMsg = "Wrong - Username / Password";

            var match = Regex.IsMatch(txtUserName.Text, "[A-Za-z0-9-_]*") && Regex.IsMatch(txtPassword.Text, @"(?=.*\d)(?=.*[a-zA-Z]).{8,99}");
            if (!match)
            {
                Logging.LogEvent(0, Request.Url, "User login: error", "Wrong - Username / Password", false);
                lblLoginResult.Text = AntiXssEncoder.HtmlEncode(errorMsg, false);
                return;
            }

            var username = txtUserName.Text;
            var password = txtPassword.Text;

            CustomerFactory.TryLogin(username, password, (customer, success) =>
                {
                    if (success)
                        Response.Redirect("Account.aspx");
                    else
                    {
                        lblLoginResult.Text = AntiXssEncoder.HtmlEncode(errorMsg, false);
                        Logging.LogEvent(0, Request.Url, "User login: failed", string.Format("Wrong Password for user: {0}", username), false);
                    }
                });
        }
    }
}